package sush.global.cammail;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import sush.global.cammail.actionbar.ActionBarActivity;
import sush.global.cammail.provider.Scheme;

public class FieldTemplateActivity extends ActionBarActivity {
	
	private int _templateId;
	private int _fieldId;
	private ContentValues _fieldRow;
	private List<Map<String, String>> _fields;
	
	private Spinner _fieldTypeSpinner;
	private CheckBox _isMultiCheck;
	private LinearLayout _dropDownValuesFrame;
	private LinearLayout _layout;
	private ListView _valuesList;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.addMenuIds(new int[] {R.id.menu_back});
		setTitle("Fields");
		setContentView(R.layout.field_template);
		
		Bundle extras = getIntent().getExtras();
		_templateId = extras.getInt("template_id");
		_fieldId = extras.getInt("field_id");
		
		_isMultiCheck = (CheckBox)getLayoutInflater().inflate(R.layout.checkbox_ismulti, null);
		_dropDownValuesFrame = (LinearLayout)getLayoutInflater().inflate(R.layout.dropdown_values_template, null);
		_valuesList = (ListView)_dropDownValuesFrame.findViewById(R.id.listview);
		_valuesList.setOnItemClickListener(valueClicked);
		
		_layout = (LinearLayout)findViewById(R.id.layout);
		
		_fieldTypeSpinner = (Spinner)findViewById(R.id.fieldtype);
		_fieldTypeSpinner.setOnItemSelectedListener(typeSelected);
		
		fillFieldsArray();
		
		loadData();
	}
	
	@Override
	public void onStop() {
		EditText labelView = (EditText)findViewById(R.id.label);
		String newText = labelView.getText().toString();
		@SuppressWarnings("unchecked")
		Map<String, String> fieldType = (Map<String, String>)_fieldTypeSpinner.getSelectedItem();
		_fieldRow.put(Scheme.getFieldTable().COLUMN_NAME_LABEL, newText);
		_fieldRow.put(Scheme.getFieldTable().COLUMN_NAME_ISMULTI, _isMultiCheck.isChecked() ? 1 : 0);
		_fieldRow.put(Scheme.getFieldTable().COLUMN_NAME_TYPE, fieldType.get("code"));
		getContentResolver().update(
				Scheme.getFieldTable().getContentUri(),
				_fieldRow,
				Scheme.getFieldTable()._ID + "=?",
				new String[] { Integer.toString(_fieldId)});
		getContentResolver().notifyChange(Scheme.getFieldTable().getContentUri(), null);
		super.onStop();
	}
	
	public void addClicked(View view) {
		EditText textView = (EditText)_dropDownValuesFrame.findViewById(R.id.value);
		String text = textView.getText().toString().trim();
		if(text.equals(""))
			return;
		
		ContentValues values = new ContentValues();
		values.put(Scheme.getDropDownValueTable().COLUMN_NAME_IDFIELD, _fieldId);
		values.put(Scheme.getDropDownValueTable().COLUMN_NAME_VALUE, text);
		getContentResolver().insert(Scheme.getDropDownValueTable().getContentUri(), values);
		
		textView.setText("");
	}
	
	public void deleteClicked(View view) {
		int position = _valuesList.getPositionForView((View)view.getParent());
		final Cursor cursor = ((SimpleCursorAdapter)_valuesList.getAdapter()).getCursor();
		cursor.moveToPosition(position);
		final ContentValues values = new ContentValues();
		DatabaseUtils.cursorRowToContentValues(cursor, values);
		
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
		alertDialog.setTitle("Are you sure?");
		alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String valueId = values.getAsString(Scheme.getDropDownValueTable()._ID);
				String whereClause = Scheme.getDropDownValueTable()._ID + "=?";
				getContentResolver().delete(
						Scheme.getDropDownValueTable().getContentUri(),
						whereClause,
						new String[] { valueId });
			}
		});
		alertDialog.setNegativeButton("Cancel", null);
		alertDialog.show();
	}
	
	private OnItemClickListener valueClicked = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> list, View view, int position, long id) {
			Cursor cursor = ((SimpleCursorAdapter)_valuesList.getAdapter()).getCursor();
			cursor.moveToPosition(position);
			final ContentValues values = new ContentValues();
			DatabaseUtils.cursorRowToContentValues(cursor, values);
			
			AlertDialog.Builder alertDialog = new AlertDialog.Builder(FieldTemplateActivity.this);
			alertDialog.setNegativeButton("Cancel", null);
			alertDialog.setTitle("Edit value");
			final EditText input = new EditText(FieldTemplateActivity.this);
			final String oldValue = values.getAsString(Scheme.getDropDownValueTable().COLUMN_NAME_VALUE);
			input.setText(oldValue);
			alertDialog.setPositiveButton("Save", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					String newText = input.getText().toString();
					if(newText.equals(oldValue)) return;
					
					values.put(Scheme.getDropDownValueTable().COLUMN_NAME_VALUE, newText);
					String valueId = values.getAsString(Scheme.getDropDownValueTable()._ID);
					getContentResolver().update(
							Scheme.getDropDownValueTable().getContentUri(),
							values,
							Scheme.getDropDownValueTable()._ID + "=?",
							new String[] { valueId });
					getContentResolver().notifyChange(Scheme.getDropDownValueTable().getContentUri(), null);
				}
			});
			alertDialog.setView(input);
			alertDialog.show();
		}
	};
	
	private void loadData() {
		if(_fieldId <= 0) {
			ContentValues values = new ContentValues();
			values.put(Scheme.getFieldTable().COLUMN_NAME_IDTEMPLATE, _templateId);
			values.put(Scheme.getFieldTable().COLUMN_NAME_LABEL, "Field");
			values.put(Scheme.getFieldTable().COLUMN_NAME_TYPE, getResources().getString(R.string.field_edittext_code));
			values.put(Scheme.getFieldTable().COLUMN_NAME_ISMULTI, false);
			Uri uri = getContentResolver().insert(Scheme.getFieldTable().getContentUri(), values);
			_fieldId = Integer.parseInt(uri.getLastPathSegment());
		}
		// Let load field
		String whereClause = Scheme.getFieldTable()._ID + "=?";
		Cursor cursor = getContentResolver().query(
				Scheme.getFieldTable().getContentUri(),
				null,
				whereClause,
				new String[] { Integer.toString(_fieldId) },
				null);
		cursor.moveToFirst();
		_fieldRow = new ContentValues();
		DatabaseUtils.cursorRowToContentValues(cursor, _fieldRow);
		cursor.close();
		
		EditText labelView = (EditText)findViewById(R.id.label);
		labelView.setText(_fieldRow.getAsString(Scheme.getFieldTable().COLUMN_NAME_LABEL));
		
		String fieldType = _fieldRow.getAsString(Scheme.getFieldTable().COLUMN_NAME_TYPE);
		if(getResources().getString(R.string.field_edittext_code).equals(fieldType)) {
			_fieldTypeSpinner.setSelection(0);
			int isChecked = _fieldRow.getAsInteger(Scheme.getFieldTable().COLUMN_NAME_ISMULTI);
			_isMultiCheck.setChecked(isChecked == 0 ? false : true);
		} else {
			_fieldTypeSpinner.setSelection(1);
		}
		
		// Load drop down values
		whereClause = Scheme.getDropDownValueTable().COLUMN_NAME_IDFIELD + "=?";
		cursor = getContentResolver().query(
				Scheme.getDropDownValueTable().getContentUri(),
				null,
				whereClause,
				new String[] { Integer.toString(_fieldId) },
				null);
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
				R.layout.listitem_with_add,
				cursor,
				new String[] { Scheme.getDropDownValueTable().COLUMN_NAME_VALUE },
				new int[] { R.id.title });
		_valuesList.setAdapter(adapter);
	}
	
	private OnItemSelectedListener typeSelected = new OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> list, View view, int position, long id) {
			@SuppressWarnings("unchecked")
			Map<String, String> item = (Map<String, String>)_fieldTypeSpinner.getAdapter().getItem(position);
			if(item.get("code").equals(getResources().getString(R.string.field_edittext_code))) {
				_layout.addView(_isMultiCheck);
				_layout.removeView(_dropDownValuesFrame);

			} else {
				_layout.removeView(_isMultiCheck);
				_layout.addView(_dropDownValuesFrame);
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
		}
	};
	
	private void fillFieldsArray() {
		_fields = new ArrayList<Map<String,String>>();
		
		Map<String, String> fieldMap;
		String code, label;
		
		fieldMap = new HashMap<String, String>();
		code = getResources().getString(R.string.field_edittext_code);
		label = getResources().getString(R.string.field_edittext);
		fieldMap.put("code", code);
		fieldMap.put("label", label);
		_fields.add(fieldMap);
		
		fieldMap = new HashMap<String, String>();
		code = getResources().getString(R.string.field_dropdown_code);
		label = getResources().getString(R.string.field_dropdown);
		fieldMap.put("code", code);
		fieldMap.put("label", label);
		_fields.add(fieldMap);
		
		SimpleAdapter adapter = new SimpleAdapter(this, _fields, android.R.layout.simple_spinner_item, 
                new String[] {"label"}, 
                new int[] { android.R.id.text1 });
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		_fieldTypeSpinner.setAdapter(adapter);
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.back, menu);
        return super.onCreateOptionsMenu(menu);
    }
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch(item.getItemId()) {
    		case R.id.menu_back:
    			finish();
    			break;
    		case R.id.home_button:
    			Intent intentHome = new Intent(this, MainActivity.class);
    			intentHome.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    			intentHome.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    			startActivity(intentHome);
    			break;
    		default:
    			return super.onOptionsItemSelected(item);
    	}
    	return true;
    }
}
